package com.joeshing.security.context;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.joeshing.security.authentication.SessionAuthenticationDetails;

public class CacheSessionManager {
	
	public static String getRemoteAddress(){
		return getDetails().getRemoteAddress();
	}
	
	public static String getSessionId(){
		return getDetails().getSessionId();
	}
	
	public static Object getSessionUser(){
		return getDetails().getUser();
	}
	
	private static SessionAuthenticationDetails getDetails(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
		SessionAuthenticationDetails details = null;
		if(securityContext!=null){
			Authentication authentication = securityContext.getAuthentication();
			if(authentication!=null&&authentication.isAuthenticated())
				details = (SessionAuthenticationDetails)authentication.getDetails();
		}
		if(details==null)
			details = new SessionAuthenticationDetails();
		return details;
	}
	
	public static boolean isAuthenticated(){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication==null)
			return false;
		else
			return authentication.isAuthenticated();
	}
	
	public static Object getSessionAttribute(String key){
		return getDetails().getSession().get(key);
	}
	
	public static void setSessionAttribute(String key,Object value){
		getDetails().getSession().put(key, value);
	}
	
	public static Object removeSessionAttribute(String key){
		return getDetails().getSession().remove(key);
	}
}
